package com.leon.datalink.web.controller;

import com.leon.datalink.core.persistence.PersistenceConfigManager;
import com.leon.datalink.web.model.PersistenceConfig;
import com.leon.datalink.web.model.PersistenceStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Actor持久化配置控制器
 * 
 * @author Leon
 * @version 1.0
 */
@RestController
@RequestMapping("/api/persistence")
public class PersistenceController {
    
    private static final Logger logger = LoggerFactory.getLogger(PersistenceController.class);
    
    /**
     * 获取持久化配置状态
     */
    @GetMapping("/status")
    public PersistenceStatus getStatus() {
        try {
            PersistenceConfigManager manager = PersistenceConfigManager.getInstance();
            
            PersistenceStatus status = new PersistenceStatus();
            status.setGlobalEnabled(manager.isGlobalPersistenceEnabled());
            status.setStrategy(manager.getStrategy());
            status.setStoragePath(manager.getStoragePath());
            status.setActorTypeConfigs(manager.getActorTypeConfigs());
            status.setInstanceConfigs(manager.getInstanceConfigs());
            
            return status;
        } catch (Exception e) {
            logger.error("Failed to get persistence status", e);
            throw new RuntimeException("获取持久化状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新全局持久化开关
     */
    @PostMapping("/global")
    public Map<String, Object> updateGlobalPersistence(@RequestBody Map<String, Boolean> request) {
        try {
            Boolean enabled = request.get("enabled");
            if (enabled == null) {
                throw new IllegalArgumentException("enabled参数不能为空");
            }
            
            PersistenceConfigManager manager = PersistenceConfigManager.getInstance();
            manager.setGlobalPersistenceEnabled(enabled);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "全局持久化配置更新成功");
            result.put("enabled", enabled);
            
            logger.info("Global persistence updated: {}", enabled);
            return result;
        } catch (Exception e) {
            logger.error("Failed to update global persistence", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 更新持久化策略
     */
    @PostMapping("/strategy")
    public Map<String, Object> updateStrategy(@RequestBody Map<String, String> request) {
        try {
            String strategy = request.get("strategy");
            if (strategy == null || strategy.trim().isEmpty()) {
                throw new IllegalArgumentException("strategy参数不能为空");
            }
            
            PersistenceConfigManager manager = PersistenceConfigManager.getInstance();
            manager.setPersistenceStrategy(strategy);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "持久化策略更新成功");
            result.put("strategy", strategy);
            
            logger.info("Persistence strategy updated: {}", strategy);
            return result;
        } catch (Exception e) {
            logger.error("Failed to update persistence strategy", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 更新Actor类型持久化配置
     */
    @PostMapping("/actor-type")
    public Map<String, Object> updateActorTypePersistence(@RequestBody Map<String, Object> request) {
        try {
            String actorType = (String) request.get("actorType");
            Boolean enabled = (Boolean) request.get("enabled");
            
            if (actorType == null || actorType.trim().isEmpty()) {
                throw new IllegalArgumentException("actorType参数不能为空");
            }
            if (enabled == null) {
                throw new IllegalArgumentException("enabled参数不能为空");
            }
            
            PersistenceConfigManager manager = PersistenceConfigManager.getInstance();
            manager.setActorTypePersistence(actorType, enabled);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "Actor类型持久化配置更新成功");
            result.put("actorType", actorType);
            result.put("enabled", enabled);
            
            logger.info("Actor type persistence updated: {} = {}", actorType, enabled);
            return result;
        } catch (Exception e) {
            logger.error("Failed to update actor type persistence", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 更新Actor实例持久化配置
     */
    @PostMapping("/instance")
    public Map<String, Object> updateInstancePersistence(@RequestBody Map<String, Object> request) {
        try {
            String nodeId = (String) request.get("nodeId");
            Boolean enabled = (Boolean) request.get("enabled");
            
            if (nodeId == null || nodeId.trim().isEmpty()) {
                throw new IllegalArgumentException("nodeId参数不能为空");
            }
            if (enabled == null) {
                throw new IllegalArgumentException("enabled参数不能为空");
            }
            
            PersistenceConfigManager manager = PersistenceConfigManager.getInstance();
            manager.setInstancePersistence(nodeId, enabled);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "Actor实例持久化配置更新成功");
            result.put("nodeId", nodeId);
            result.put("enabled", enabled);
            
            logger.info("Actor instance persistence updated: {} = {}", nodeId, enabled);
            return result;
        } catch (Exception e) {
            logger.error("Failed to update instance persistence", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 重新加载持久化配置
     */
    @PostMapping("/reload")
    public Map<String, Object> reloadConfig() {
        try {
            PersistenceConfigManager manager = PersistenceConfigManager.getInstance();
            manager.reloadConfiguration();
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "持久化配置重新加载成功");
            
            logger.info("Persistence configuration reloaded");
            return result;
        } catch (Exception e) {
            logger.error("Failed to reload persistence configuration", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "重新加载失败: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 获取持久化统计信息
     */
    @GetMapping("/statistics")
    public Map<String, Object> getStatistics() {
        try {
            PersistenceConfigManager manager = PersistenceConfigManager.getInstance();
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("globalEnabled", manager.isGlobalPersistenceEnabled());
            statistics.put("strategy", manager.getStrategy());
            statistics.put("actorTypeCount", manager.getActorTypeConfigs().size());
            statistics.put("instanceCount", manager.getInstanceConfigs().size());
            statistics.put("storagePath", manager.getStoragePath());
            
            return statistics;
        } catch (Exception e) {
            logger.error("Failed to get persistence statistics", e);
            throw new RuntimeException("获取持久化统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 删除Actor类型配置
     */
    @DeleteMapping("/actor-type/{actorType}")
    public ResponseEntity<String> deleteActorTypeConfig(@PathVariable String actorType) {
        try {
            PersistenceConfigManager manager = PersistenceConfigManager.getInstance();
            manager.removeActorTypePersistence(actorType);

            logger.info("Deleted actor type configuration: {}", actorType);
            return ResponseEntity.ok("Actor type configuration deleted successfully");
        } catch (Exception e) {
            logger.error("Failed to delete actor type configuration: " + actorType, e);
            return ResponseEntity.status(500).body("删除Actor类型配置失败: " + e.getMessage());
        }
    }

    /**
     * 删除实例配置
     */
    @DeleteMapping("/instance/{instanceId}")
    public ResponseEntity<String> deleteInstanceConfig(@PathVariable String instanceId) {
        try {
            PersistenceConfigManager manager = PersistenceConfigManager.getInstance();
            manager.removeInstancePersistence(instanceId);

            logger.info("Deleted instance configuration: {}", instanceId);
            return ResponseEntity.ok("Instance configuration deleted successfully");
        } catch (Exception e) {
            logger.error("Failed to delete instance configuration: " + instanceId, e);
            return ResponseEntity.status(500).body("删除实例配置失败: " + e.getMessage());
        }
    }

    /**
     * 重置持久化配置
     */
    @PostMapping("/reset")
    public ResponseEntity<String> resetConfig() {
        try {
            PersistenceConfigManager manager = PersistenceConfigManager.getInstance();
            manager.initialize(); // 重新初始化配置

            logger.info("Reset persistence configuration");
            return ResponseEntity.ok("Configuration reset successfully");
        } catch (Exception e) {
            logger.error("Failed to reset configuration", e);
            return ResponseEntity.status(500).body("重置配置失败: " + e.getMessage());
        }
    }
}
